{
 "cells": [
  {
   "metadata": {
    "collapsed": true
   },
   "cell_type": "markdown",
   "source": [
    "#### 下面是最新的基于LCEL构建的Chains\n",
    "    create_sql_query_chain\n",
    "    create_stuff_documents_chain\n",
    "    create_openai_fn_runnable\n",
    "    create_structured_output_runnable\n",
    "    load_query_constructor_runnable\n",
    "    create_history_aware_retriever\n",
    "    create_retrieval_chain"
   ],
   "id": "c3cccd54fd650c33"
  },
  {
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "cell_type": "markdown",
   "source": [
    "##### create_sql_query_chain\n",
    "    create_sql_query_chain，sql查询链，是闯进啊生成sql查询的链，用于将自然语言转换成数据库的sql查询"
   ],
   "id": "6cbf95323668aba1"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from langchain_community.utilities import SQLDatabase\n",
    "from langchain.chains.sql_database.query import create_sql_query_chain\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "\n",
    "os.environ['OPENAI_BASE_URL'] = 'https://vip.apiyi.com/v1'\n",
    "os.environ['OPENAI_API_KEY'] = 'sk-xU64G4hXJ4L47ko3764958119dB245D2BdEcE528767dA1Da'\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "db_user = \"root\"\n",
    "db_password = \"Ykwl1Mt9j0cBIY\"\n",
    "db_host = \"8.133.184.112\"\n",
    "db_port = \"3381\"\n",
    "db_name = \"chemlab2.0\"\n",
    "\n",
    "db = SQLDatabase.from_uri(f\"mysql+pymysql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}\")\n",
    "\n",
    "# print(\"哪种数据库：\", db.dialect)\n",
    "# print(\"获取数据库表：\", db.get_usable_table_names())\n",
    "# 执行查询\n",
    "# res = db.run(\"select * from zhybdata\")\n",
    "# print(res)\n",
    "chain = create_sql_query_chain(chat_model, db)\n",
    "response = chain.invoke({\"question\": \"表中一共有多少数据?\", \"table_names_to_use\": [\"zhybdata\"]})\n",
    "print(response)"
   ],
   "id": "7b90c4bad7002272",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "##### create_stuff_documents_chain(了解)\n",
    "create_stuff_documents_chain用于将多个文档内容合并成单个长文本的链式工具，并一次性传递给LLM处理(而不是分多次处理)\n",
    "适合场景：\n",
    "    保持上下文完整，适合需要全局理解所有文档内容的任务，如总结、问答\n",
    "    适合处理少量/中等长度文档的场景"
   ],
   "id": "108c5327694d1971"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
